var path = require("path");
var express = require("express");
var jwt = require('express-jwt');
var bodyParser = require('body-parser');
var tokenManager = require('./config/token_manager');
var secret = require('./config/secret');
//Routes
var routes = {};
routes.users = require('./route/user.js');
routes.posts = require('./route/posts.js')
routes.orders = require('./route/order.js')
routes.home = require('./route/home.js')
routes.gold = require('./route/gold.js')

var app = express();
var serverPort = process.env.PORT || 4000;
app.listen(serverPort, "0.0.0.0", function (err) { // 192.168.7.148
  if (err) {
    console.log(err);
    return;
  }
  console.log("Listening at http://localhost:" + serverPort);
});

app.use(function(req, res, next) {
  // res.header("Access-Control-Allow-Origin", "*"); 
  res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, Authorization");
  // res.header('Access-Control-Allow-Methods: GET, POST, PUT,DELETE');
  next();
});

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(express.static(path.join(__dirname, 'html')))

// index.html//默认跳转主页
app.get('/', function (req, res) {
    res.sendFile(__dirname + '/index.html');
});

//获取金价
app.get('/gold/index', routes.gold.index); 


//Logout
app.get('/user/logout', jwt({secret: secret.secretToken}), routes.users.logout); 

//用户登录
app.post('/user/signin', routes.users.signin); 

//注册用户列表
app.post('/user/list', jwt({secret: secret.secretToken}), tokenManager.verifyToken,  routes.users.list); 

//获取订单列表
app.post('/order/list', jwt({secret: secret.secretToken}), tokenManager.verifyToken,  routes.orders.list);

//更新订单
app.post('/order/update', jwt({secret: secret.secretToken}), tokenManager.verifyToken,  routes.orders.update);

//删除订单
app.get('/order/cancelOrder', jwt({secret: secret.secretToken}), tokenManager.verifyToken, routes.orders.cancelOrder);

//新增商品
app.post('/posts/add', jwt({secret: secret.secretToken}), tokenManager.verifyToken, routes.posts.addPost); 

//查询商品
app.post('/posts/query', jwt({secret: secret.secretToken}), tokenManager.verifyToken, routes.posts.queryList); 

//更新商品
app.post('/posts/update', jwt({secret: secret.secretToken}), tokenManager.verifyToken, routes.posts.updatePost); 

//设置首页参数
app.post('/home/setting', jwt({secret: secret.secretToken}), tokenManager.verifyToken, routes.home.setting); 

//获取首页参数
app.get('/home/getting', jwt({secret: secret.secretToken}), tokenManager.verifyToken, routes.home.getting); 


process.on('uncaughtException', function(err){
  console.log(err);
})

